package ulliver.co.th;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;

//import com.google.api.services.bigquery.Bigquery.Jobs.Insert;

/**
 * Minimal example BigQuery App Engine servlet.
 */

public class BigTableServlet extends HttpServlet {
	private final static Logger LOGGER = Logger.getLogger(BigTableServlet.class
			.getName());

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String firstName = request.getParameter("firstName").toString();
		String lastName = request.getParameter("lastName").toString();
		// SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");
		String hireDateStr = request.getParameter("hireDate");
		System.out.println(firstName + " - " + lastName + " - " + hireDateStr);
		String[] list = hireDateStr.split("-");
		// Date hireDate = new Date(request.getParameter("hireDate"));
		int year = Integer.parseInt(list[0]) - 1900;
		int month = Integer.parseInt(list[1]) - 1;
		int day = Integer.parseInt(list[2]);
		Date hireDate = new Date(year, month, day);
		System.out.println(hireDate);
		if (request.getParameter("key") != null
				&& (!request.getParameter("key").toString()
						.equalsIgnoreCase(""))) {
			String key = (String) request.getParameter("key");
			try {
				System.out.println("********************Begin update");
				updateEmployee(key, firstName, lastName, hireDate);
			} catch (EntityNotFoundException e) {
				e.printStackTrace();
			}
		} else {
			System.out.println("********************Begin insert");
			insertEmployee(firstName, lastName, hireDate);
		}
		response.sendRedirect("/bigtable");
	}

	public void insertEmployee(String firstName, String lastName, Date hireDate)
			throws IOException {
		// Insert
		DatastoreService datastore = DatastoreServiceFactory
				.getDatastoreService();
		Entity employee = new Entity("Employee");
		employee.setProperty("firstName", firstName);
		employee.setProperty("lastName", lastName);
		employee.setProperty("hireDate", hireDate);
		datastore.put(employee);

	}

	public void updateEmployee(String keyStr, String firstName,
			String lastName, Date hireDate) throws IOException,
			EntityNotFoundException {
		// Insert
		DatastoreService datastore = DatastoreServiceFactory
				.getDatastoreService();
		Key employeeKey = KeyFactory.stringToKey(keyStr);
		Entity employee = datastore.get(employeeKey);
		datastore.delete(employeeKey);
		employee.setProperty("firstName", firstName);
		employee.setProperty("lastName", lastName);
		employee.setProperty("hireDate", hireDate);
		datastore.put(employee);

	}

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		if (request.getParameter("key") != null
				&& (!request.getParameter("key").toString()
						.equalsIgnoreCase(""))) {
			String key = (String) request.getParameter("key");
			System.out.println(key);
			PrintWriter out = response.getWriter();
			out.println("Delete success");
			// Delete:
			System.out.println("********************Begin delete");
			DatastoreService datastore = DatastoreServiceFactory
					.getDatastoreService();
			Key employeeKey = KeyFactory.stringToKey(key);
			datastore.delete(employeeKey);
			return;
		} else {
			System.out.println("********************Begin Select");
			try {
				response.setContentType("text/plain");
				response.setCharacterEncoding("UTF-8");

				// Query:
				DatastoreService datastore = DatastoreServiceFactory
						.getDatastoreService();
				// Use class Query to assemble a query
				Query q = new Query("Employee");

				// Use PreparedQuery interface to retrieve results
				PreparedQuery pq = datastore.prepare(q);

				List<EmployeeModel> listRecord = new ArrayList<EmployeeModel>();
				for (Entity result : pq.asIterable()) {
					String key = KeyFactory.keyToString(result.getKey());
					String firstName = (String) result.getProperty("firstName");
					String lastName = (String) result.getProperty("lastName");
					Date hireDate = (Date) result.getProperty("hireDate");
					// System.out.println(firstName + " " + lastName + ", " +
					// hireDate2.toGMTString());
					EmployeeModel record = new EmployeeModel();
					record.setFirstName(firstName);
					record.setLastName(lastName);
					record.setHireDate(hireDate);
					record.setKey(key);
					listRecord.add(record);
				}
				request.setAttribute("listRecord", listRecord);
				request.getRequestDispatcher("result.jsp").forward(request,
						response);
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}
}
